package com.collectplus.express.passport;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.model.LatLngBounds;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.collectplus.express.R;
import com.collectplus.express.app.Intents;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.PassportDetailBean;
import com.collectplus.express.view.RatingBar;
import com.shouhuobao.map.BikingRouteOverlay;

import droid.frame.activity.base.BaseViewStub;
import droid.frame.utils.GlideUtil;
import droid.frame.utils.lang.Str;

/**
 * Created by lidandan on 2018/1/3.
 * 新版passport同城  parcelStatus 4 火箭侠去取  19 火箭侠去送  200 已签收
 */
public class NewPassportCityWideRouteOperate extends BaseViewStub {

    private BaiduMap mBaiduMap;
    private MapView mMapView = null;
    private PlanNode sNode = null;
    private PlanNode eNode = null;
    private RoutePlanSearch mSearch;

    private View courierToTakeView = null;//火箭侠去取的布局

    private PassportDetailBean item;

    public NewPassportCityWideRouteOperate(Activity context, int resId) {
        super(context, resId);
    }

    public void loadLayout(final PassportDetailBean item) {
        super.inflate();
        this.item = item;
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        //普通地图
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        mMapView.showZoomControls(false);//隐藏缩放按钮
        mMapView.showScaleControl(false);//隐藏比例尺
        mBaiduMap.setMyLocationEnabled(false);
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(listener);
        routeplanToNavi();

        ImageView photoIv = (ImageView) findViewById(R.id.passport_courier_photo_img);
        TextView nickNameTv = (TextView) findViewById(R.id.passport_station_nic_name);
        TextView nameTv = (TextView) findViewById(R.id.passport_courier_name);
        TextView cardTv = (TextView) findViewById(R.id.passport_station_code_tv);
        RatingBar ratingBar = (RatingBar) findViewById(R.id.citywide_rb_five);
        TextView ratingTv = (TextView) findViewById(R.id.citywide_rating_tv);
        if (Str.isNotEmpty(item.getImagePath())) {
            GlideUtil.loadImage(getContext(), item.getImagePath(), 0, photoIv);
        } else {
            photoIv.setImageResource(R.drawable.visit_place_holder_icon);
        }

        nickNameTv.setText(item.getNickName());
        nameTv.setText("(" + item.getName() + ")");
        cardTv.setText(item.getCardNumber());
        if (item.getPraiseNum() > 0) {
            ratingBar.setIntegerMark(false);
            ratingBar.setStarMark(item.getPraiseNum());
            ratingTv.setText(item.getPraiseNum() + "分");
            ratingTv.setTextColor(Color.parseColor("#E32141"));
            ratingBar.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    return true;
                }
            });
        }

        findViewById(R.id.passport_courier_call).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intents.dialOrCall(item.getPhone());
            }
        });
    }

    private void routeplanToNavi() {
        mBaiduMap.clear();
        //包裹在取的路上 寄件人的坐标和火箭侠的坐标
        if (Const.ParcelStatus.payed == item.getParcelStatus()) {
            courierToTakeView = LayoutInflater.from(getContext()).inflate(R.layout.passport_courier_location_layout, null, false);
            ((TextView) courierToTakeView.findViewById(R.id.arriver_time_tv)).setText(item.getReciveTime());
            ((TextView) courierToTakeView.findViewById(R.id.distance_tip_tv)).setText("距您的位置" + item.getReceiverDistance() + "km");
            LatLng northeast = new LatLng(Math.max(item.getUserLatitude(), item.getLatitude()), Math.max(item.getUserLongitude(), item.getLongitude()));
            LatLng southwest = new LatLng(Math.min(item.getUserLatitude(), item.getLatitude()), Math.min(item.getUserLongitude(), item.getLongitude()));
            LatLngBounds bounds = new LatLngBounds.Builder().include(northeast).include(southwest).build();
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(bounds);
            sNode = PlanNode.withLocation(new LatLng(item.getLatitude(), item.getLongitude()));
            eNode = PlanNode.withLocation(new LatLng(item.getUserLatitude(), item.getUserLongitude()));
        }
        //包裹在送的路上 收件人的坐标和火箭侠的坐标
        else if (Const.ParcelStatus.collectionsuccess == item.getParcelStatus()) {
            courierToTakeView = LayoutInflater.from(getContext()).inflate(R.layout.passport_courier_location_layout, null, false);
            ((TextView) courierToTakeView.findViewById(R.id.arriver_time_tv)).setText(item.getOverTime());
            ((TextView) courierToTakeView.findViewById(R.id.distance_tip_tv)).setText("距收件人位置" + item.getUserDistance() + "km");
            LatLng northeast = new LatLng(Math.max(item.getReceiverLatitude(), item.getLatitude()), Math.max(item.getReceiverLongitude(), item.getLongitude()));
            LatLng southwest = new LatLng(Math.min(item.getReceiverLatitude(), item.getLatitude()), Math.min(item.getReceiverLongitude(), item.getLongitude()));
            LatLngBounds bounds = new LatLngBounds.Builder().include(northeast).include(southwest).build();
            MapStatusUpdate u = MapStatusUpdateFactory.newLatLngBounds(bounds);
            sNode = PlanNode.withLocation(new LatLng(item.getLatitude(), item.getLongitude()));
            eNode = PlanNode.withLocation(new LatLng(item.getReceiverLatitude(), item.getReceiverLongitude()));
        }
        //包裹已签收
        else if (Const.ParcelStatus.unEvaluate == item.getParcelStatus()) {
            courierToTakeView = LayoutInflater.from(getContext()).inflate(R.layout.passport_receiver_location_layout, null, false);
            ((TextView) courierToTakeView.findViewById(R.id.order_finish_tip_tv)).setText("已送达，共用时" + item.getCountTime() + "分钟");
            LatLng northeast = new LatLng(Math.max(item.getReceiverLatitude(), item.getUserLatitude()), Math.max(item.getReceiverLongitude(), item.getUserLongitude()));
            LatLng southwest = new LatLng(Math.min(item.getReceiverLatitude(), item.getUserLongitude()), Math.min(item.getReceiverLongitude(), item.getUserLongitude()));
            LatLngBounds bounds = new LatLngBounds.Builder().include(northeast).include(southwest).build();
            MapStatusUpdateFactory.newLatLngBounds(bounds);
            sNode = PlanNode.withLocation(new LatLng(item.getUserLatitude(), item.getUserLongitude()));
            eNode = PlanNode.withLocation(new LatLng(item.getReceiverLatitude(), item.getReceiverLongitude()));
        }
        if (sNode != null && eNode != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mSearch.bikingSearch((new BikingRoutePlanOption()).from(sNode).to(eNode));
                }
            }).start();
        }
    }

    OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
        @Override
        public void onGetWalkingRouteResult(WalkingRouteResult result) {
            //获取步行线路规划结果
        }

        @Override
        public void onGetTransitRouteResult(TransitRouteResult result) {
            //获取公交换乘路径规划结果
        }

        @Override
        public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

        }

        @Override
        public void onGetDrivingRouteResult(DrivingRouteResult result) {
        }

        @Override
        public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

        }

        @Override
        public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
            if (bikingRouteResult == null || bikingRouteResult.error != SearchResult.ERRORNO.NO_ERROR) {
                return;
            }
            if (bikingRouteResult.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                //起终点或途经点地址有岐义，通过以下接口获取建议查询信息
                //result.getSuggestAddrInfo()
                return;
            }
            if (bikingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
                try {
                    BikingRouteOverlay overlay = new MyBikingRouteOverlay(mBaiduMap);//路线覆盖物，MyDrivingRouteOverlay代码下面给出
                    //            mBaidumap.setOnMarkerClickListener(overlay);
                    overlay.setData(bikingRouteResult.getRouteLines().get(0));
                    overlay.addToMap();
                    overlay.zoomToSpan();
                    float zome = mBaiduMap.getMapStatus().zoom;
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(zome - 1));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    };

    private class MyBikingRouteOverlay extends BikingRouteOverlay {
        /**
         * 构造函数
         *
         * @param baiduMap 该DrivingRouteOvelray引用的 BaiduMap
         */
        public MyBikingRouteOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        @Override
        public BitmapDescriptor getStartMarker() {
            //覆写此方法以改变默认起点图标
            //包裹在取的路上 寄件人的坐标和火箭侠的坐标
            if (Const.ParcelStatus.payed == item.getParcelStatus()) {
                return BitmapDescriptorFactory.fromView(courierToTakeView);
            }
            //包裹在送的路上 收件人的坐标和火箭侠的坐标
            else if (Const.ParcelStatus.collectionsuccess == item.getParcelStatus()) {
                return BitmapDescriptorFactory.fromView(courierToTakeView);
            }
            //包裹已签收
            else if (Const.ParcelStatus.unEvaluate == item.getParcelStatus()) {
                return BitmapDescriptorFactory.fromResource(R.drawable.passport_samecity_send_icon);
            }
            return null;
            //这里可以使用BitmapDescriptorFactory.fromView(view)实现自定义view覆盖物，自定义覆盖物请关注以后的文章。
        }

        @Override
        public int getLineColor() {
            // TODO Auto-generated method stub
            //覆写此方法以改变默认绘制颜色
            //Returns:
            //线颜色
            return super.getLineColor();
        }

        @Override
        public BitmapDescriptor getTerminalMarker() {
            //覆写此方法以改变默认终点图标
            //包裹在取的路上 寄件人的坐标和火箭侠的坐标
            if (Const.ParcelStatus.payed == item.getParcelStatus()) {
                return BitmapDescriptorFactory.fromResource(R.drawable.passport_samecity_send_icon);
            }
            //包裹在送的路上 收件人的坐标和火箭侠的坐标
            else if (Const.ParcelStatus.collectionsuccess == item.getParcelStatus()) {
                return BitmapDescriptorFactory.fromResource(R.drawable.passport_samecity_receive_icon);
            }
            //包裹已签收
            else if (Const.ParcelStatus.unEvaluate == item.getParcelStatus()) {
                return BitmapDescriptorFactory.fromView(courierToTakeView);
            }
            return null;
        }

        @Override
        public boolean onRouteNodeClick(int i) {
            // TODO Auto-generated method stub
            //覆写此方法以改变默认点击处理
            return true;
        }
    }

    protected void onResume() {
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (mMapView != null) {
            mMapView.onResume();
        }
    }

    public void onSaveInstanceState(Bundle outState) {
        if (mMapView != null) {
            mMapView.onSaveInstanceState(outState);
        }
    }

    public void onPause() {
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (mMapView != null) {
            mMapView.onPause();
        }
    }

    public void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (mSearch != null) {
            mSearch.destroy();
        }
        if (mBaiduMap != null) {
            mBaiduMap.clear();
        }
        if (mSearch != null) {
            mSearch.destroy();
        }
        if (mMapView != null) {
            mMapView.onDestroy();
        }
        super.onDestroy();
    }

}
